package com.rpay.admin.util.render;

import com.rpay.admin.util.http.ContentType;
import com.rpay.common.util.json.Jsoner;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Administrator on 2017/5/18 0018.
 */
@Component
public class JsonRender extends Render {

    @Override
    public void render(HttpServletRequest request, HttpServletResponse response, Object out) {
        if (out != null) {
            if (out instanceof InputStream) {
                byte[] buffer = new byte[4 * 1024];
                int len = 0;
                try {
                    while ((len = ((InputStream) out).read(buffer)) != -1) {
                        response.getOutputStream().write(buffer, 0, len);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                response.setContentType(ContentType.JSON.value());
                if (out instanceof String) {
                    if (Jsoner.isJson((String) out)) {
                        write(request, response, (String) out);
                    } else {
                        write(request, response, "\"" + out + "\"");
                    }
                } else {
                    String json = Jsoner.toJSON(out);
                    write(request, response, json);
                }
            }
        }
    }
}
